package com.example.lj.uav.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.example.lj.uav.R;
import com.example.lj.uav.utils.OnUIUtils;

import java.util.List;

import dji.common.error.DJIError;
import dji.common.util.CommonCallbacks;
import dji.sdk.media.FetchMediaTask;
import dji.sdk.media.FetchMediaTaskContent;
import dji.sdk.media.FetchMediaTaskScheduler;
import dji.sdk.media.MediaFile;
import dji.sdk.media.MediaManager;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

public class PhotoAdapter extends PagerAdapter {
    private Context context;
    private List<MediaFile> files;
    private SparseArray<View> cacheView;
    private Handler mHandler;
    private ViewGroup containerTemp;
    private FetchMediaTaskScheduler scheduler;
    private MediaManager manager;
    private static final int PHOTO_CLICKED = 0;
    private static final int PLAY_VIDEO = 1;

    public PhotoAdapter(Context context, List<MediaFile> files, Handler mHandler, FetchMediaTaskScheduler scheduler, MediaManager manager) {
        this.context = context;
        this.files = files;
        this.mHandler = mHandler;
        cacheView = new SparseArray<>(files.size());
        this.scheduler = scheduler;
        this.manager = manager;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, final int position) {
        if(containerTemp == null) containerTemp = container;

        View view = cacheView.get(position);

        if(view == null){
            view = LayoutInflater.from(context).inflate(R.layout.photo_browser_image_view,container,false);
            view.setTag(position);
            final PhotoView image = view.findViewById(R.id.iv_photo_image_item);
            final PhotoViewAttacher photoViewAttacher = new PhotoViewAttacher(image);
            final FetchMediaTask task = new FetchMediaTask(files.get(position), FetchMediaTaskContent.PREVIEW, new FetchMediaTask.Callback() {
                @Override
                public void onUpdate(MediaFile mediaFile, FetchMediaTaskContent fetchMediaTaskContent, DJIError error) {
                    if (null == error) {
                        if (mediaFile.getPreview() != null) {
                            Bitmap previewBitmap = mediaFile.getPreview();
                            image.setImageBitmap(previewBitmap);
                            photoViewAttacher.update();
                        }
                    }
                }
            });

            scheduler.resume(new CommonCallbacks.CompletionCallback() {
                @Override
                public void onResult(DJIError error) {
                    if (error == null) {
                        scheduler.moveTaskToNext(task);
                    }
                }
            });
            photoViewAttacher.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
                @Override
                public void onPhotoTap(View view, float x, float y) {
                    mHandler.sendEmptyMessage(PHOTO_CLICKED);
                }
            });
            final ImageView iv_play = view.findViewById(R.id.iv_play);
            MediaFile.MediaType type = files.get(position).getMediaType();
            if (type==MediaFile.MediaType.JPEG||type==MediaFile.MediaType.RAW_DNG
                    ||type==MediaFile.MediaType.TIFF||type==MediaFile.MediaType.PANORAMA
                    ||type==MediaFile.MediaType.SHALLOW_FOCUS){
                iv_play.setVisibility(View.GONE);

            }else{
                iv_play.setVisibility(View.VISIBLE);
                final View finalView = view;
                iv_play.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View clickView) {
                        showControlBar(finalView);
//                        Message msg = mHandler.obtainMessage();
//                        msg.what = PLAY_VIDEO;
//                        msg.arg1 = position;
//                        mHandler.sendMessage(msg);
                        playVideo(position);
                    }
                });
            }
            view.findViewById(R.id.iv_pause_start_video).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    manager.pause(new CommonCallbacks.CompletionCallback() {
                        @Override
                        public void onResult(DJIError djiError) {
                            if (null==djiError){
                                iv_play.setVisibility(View.VISIBLE);
                            }
                        }
                    });
                }
            });

            view.findViewById(R.id.iv_stop_video).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    manager.stop(new CommonCallbacks.CompletionCallback() {
                        @Override
                        public void onResult(DJIError djiError) {
                            if (null==djiError){
                                iv_play.setVisibility(View.VISIBLE);
                            }
                        }
                    });
                }
            });
            cacheView.put(position,view);
        }
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        View view = (View) object;
        container.removeView(view);
    }

    @Override
    public int getCount() {
        return files.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view==object;
    }

    private void showControlBar(View view){
        view.findViewById(R.id.iv_photo_image_item).setVisibility(View.GONE);
        view.findViewById(R.id.iv_play).setVisibility(View.VISIBLE);
        view.findViewById(R.id.FPVWidget).setVisibility(View.VISIBLE);
        view.findViewById(R.id.ll_video_control).setVisibility(View.VISIBLE);
    }

    private void hideControlBar(View view){
        view.findViewById(R.id.iv_photo_image_item).setVisibility(View.VISIBLE);
        view.findViewById(R.id.iv_play).setVisibility(View.GONE);
        view.findViewById(R.id.FPVWidget).setVisibility(View.GONE);
        view.findViewById(R.id.ll_video_control).setVisibility(View.GONE);
    }

    private void playVideo(int position){
        MediaFile selectedMediaFile = files.get(position);
        if ((selectedMediaFile.getMediaType() == MediaFile.MediaType.MOV) || (selectedMediaFile.getMediaType() == MediaFile.MediaType.MP4)) {
            manager.playVideoMediaFile(selectedMediaFile, new CommonCallbacks.CompletionCallback() {
                @Override
                public void onResult(DJIError error) {
                    if (null != error) {
                        OnUIUtils.setToast("Play Video Failed" + error.getDescription());
                    }
                }
            });
        }
    }
}
